package com.yuntsg.nnsfcp.service.front.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.entity.SearchEntity;
import com.yuntsg.nnsfcp.front.entity.*;
import com.yuntsg.nnsfcp.front.mapper.*;
import com.yuntsg.nnsfcp.service.front.CheckService;
import com.yuntsg.nnsfcp.service.front.Constants;
import com.yuntsg.nnsfcp.service.front.OrderService;
import com.yuntsg.nnsfcp.service.front.WhetherArticleEnteredService;
import com.yuntsg.nnsfcp.service.front.pojo.OrderFileList;
import com.yuntsg.nnsfcp.service.front.pojo.QueryScopeDetail;
import com.yuntsg.nnsfcp.service.front.pojo.ReturnOrderStatus;
import com.yuntsg.nnsfcp.service.front.pojo.SendCreateId;
import com.yuntsg.nnsfcp.service.front.ut.UniCodeUtil;
import com.yuntsg.nnsfcp.util.SendSms;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.yuntsg.nnsfcp.service.front.ut.DateUtil.*;

/**
 * 处理委托单
 *
 * @author ：ljx
 * @date ：Created in 2019/5/31
 */
@Slf4j
@Service
@Component
public class OrderServiceImpl implements OrderService, Serializable {
    @Resource
    BackconfigMapper backconfigMapper;
    @Resource
    private OrderBaseInfoMapper orderBaseInfoMapper;
    @Resource
    private OrderIndexTimeMapper orderIndexTimeMapper;
    @Resource
    private WhetherArticleEnteredService whetherArticleEntered;
    @Resource
    private WosdetailMapper wosdetailMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private OrderStatusMapper orderStatusMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private SendSms sendSms;
    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private TRoleMapper roleMapper;
    @Resource
    private InvoiceInfoMapper invoiceInfoMapper;
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private CheckService checkService;
    //@Resource
    //private SendEmailService sendEmailService;
    @Resource
    private CnkiDetailMapper cnkiDetailMapper;


    /**
     * 生成 查收,新,引 各自的编号 2019360YZH0200***
     *
     * @param orderBaseInfo 订单实体
     * @return 编号
     */
    @Override
    public String setProjectNo(OrderBaseInfo orderBaseInfo) {
        Calendar calendar = Calendar.getInstance();
        String year = "" + calendar.get(Calendar.YEAR);

        List<OrderBaseInfo> dbOrderList = null;
        if (orderBaseInfo.getType() != null) {
            Integer type = orderBaseInfo.getType();
            if (Constants.CX.equals(type)) {
                //通过类型,获取类型下所有订单
                dbOrderList
                        = orderBaseInfoMapper.selectList(new QueryWrapper<OrderBaseInfo>()
                        .select("apply_id", "type", "project_no")
                        .eq("type", orderBaseInfo.getType())
                        .orderByAsc("apply_id"));
            } else {
                //通过类型,获取类型下所有订单
                dbOrderList = orderBaseInfoMapper.selectList(new QueryWrapper<OrderBaseInfo>()
                        .select("apply_id", "type", "project_no")
                        .eq("type", 1)
                        .or(wrapper -> wrapper.eq("type", 2))
                        .orderByAsc("apply_id"));
            }
        }
        String temp = null;
        if (dbOrderList == null || dbOrderList.size() == 0) {
            //初始值
            Integer type = orderBaseInfo.getType();
            if (Constants.CS.equals(type) || Constants.CY.equals(type)) {
                temp = "Y" + year + "0001";
            } else if (Constants.CX.equals(type)) {
                temp = year + "360YZH020001";
            }
        } else {
            //得到该类型下最后一个委托单
            OrderBaseInfo order = dbOrderList.get(dbOrderList.size() - 1);
            Integer type = order.getType();
            String tempOrderNo = order.getProjectNo();

            //判断空
            if (StringUtils.isEmpty(tempOrderNo)) {
                for (int i = dbOrderList.size() - 1; i > 0; i--) {
                    OrderBaseInfo tempOrder = dbOrderList.get(i);
                    String projectNo = tempOrder.getProjectNo();
                    if (StringUtils.isNotEmpty(tempOrderNo)) {
                        tempOrderNo = projectNo;
                        break;
                    }
                }
            }

            //数据库的年份  编号中切割出来的年份
            String dbYear = null;
            if (Constants.CS.equals(type) || Constants.CY.equals(type)) {

                if (StringUtils.isEmpty(tempOrderNo)) {
                    temp = "Y" + year + "0001";
                    return temp;
                }

                //Y20190001
                String code = tempOrderNo.substring(tempOrderNo.length() - 6);
                int num1 = Integer.parseInt(code) + 1;
                dbYear = tempOrderNo.substring(1, 5);

                //新的一年从零开始
                if (!year.equals(dbYear)) {
                    num1 = 1;
                }

                //编号工具
                DecimalFormat df = new DecimalFormat("0000");
                String format = df.format(num1);
                temp = "Y" + year + format;
            } else {

                if (StringUtils.isEmpty(tempOrderNo)) {
                    temp = year + "360YZH020001";
                    return temp;
                }

                dbYear = tempOrderNo.substring(0, 4);
                String codeStr = tempOrderNo.substring(tempOrderNo.length() - 5);
                int num = Integer.parseInt(codeStr) + 1;

                //新的一年从零开始
                if (!year.equals(dbYear)) {
                    num = 20001;
                }

                DecimalFormat df = new DecimalFormat("000000");
                String format = df.format(num);
                temp = year + "360YZH" + format;
            }
        }
        return temp;
    }

    /**
     * 生成委托单编号
     *
     * @return 编号
     */
    @Override
    public String setApplyId() {
        //委托单初始值
        String applyId = "592000001";
        //获取所有编号
        List<OrderBaseInfo> orderApplyId =
                orderBaseInfoMapper.selectList(new QueryWrapper<OrderBaseInfo>()
                        .select("apply_id").orderByAsc("apply_id"));
        //获取不到,初始化值
        if (orderApplyId.size() == 0) {
            return applyId;
        }
        //取出集合中最后一个数据,applyId参数数值+1
        int intApplyId = Integer.parseInt(orderApplyId.get(orderApplyId.size() - 1).getApplyId()) + 1;
        //转换字符串返回
        return String.valueOf(intApplyId);
    }

    @Override
    public Integer updateById2(HttpServletRequest request, OrderBaseInfo orderBaseInfo) {
        return 0;
    }

    /**
     * 创建委托单,生成订单号
     *
     * @param serverOrder type + userId
     * @return
     */
    @Override
    public Object createOrder(HttpServletRequest request, OrderBaseInfo serverOrder) {

        Object uidObj = request.getAttribute("u_id");
        System.out.println("输出测试uidobjec" + uidObj);
        CheckUtil.notNull(uidObj, "非法操作订单");
        Integer frontUserId = Integer.valueOf(uidObj + "");
        //添加判断当天有没有超限超限则提示无法提交
        Backconfig backconfig = backconfigMapper.selectById(6);
        Integer flag = backconfig.getFlag();
        Integer i = Math.toIntExact(orderBaseInfoMapper.selectCount(new QueryWrapper<OrderBaseInfo>().between("addtime", parseLongtoLocalDateTime(todayStartLong()), parseLongtoLocalDateTime(todayEndLong()))));
        if (flag < i) {
            CheckUtil.check(false, "当天已收到的全部委托已超过限制,请明天提交");
        }


        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>()
                .eq("id", frontUserId).eq("is_delete", 0));
        CheckUtil.notNull(userInfo, "创建订单失败 code:" + serverOrder.getUserId());
        CheckUtil.check(serverOrder.getUserId().equals(frontUserId), "非法操作订单");

        //暂时放这里测试邮件发送
        /*String[] sendTo = {"554197753@qq.com", "gechengrui09@163.com"};
        String mailTitle = "查新系统";
        String content = "情报所校内服务器, " + userInfo.getName() + "创建了一个订单:" + setApplyId() + "  创建时间:" + DateUtil
        .getFormatYearStr("");
        boolean b = sendEmailService.sendTextEmail(sendTo, mailTitle, content);*/

        //查询用户下是否有未完成的订单
        List<OrderBaseInfo> dbOrderList = orderBaseInfoMapper.selectList(new QueryWrapper<OrderBaseInfo>()
                .select("id", "type", "apply_id")
                .eq("order_status_type", 0)
                .eq("user_id", userInfo.getId()));
        //未完成,返回订单
        if (dbOrderList != null && dbOrderList.size() > 0) {
            for (OrderBaseInfo dbOrder : dbOrderList) {
                Integer dbType = dbOrder.getType();
                Integer serverType = serverOrder.getType();
                if (dbType.equals(serverType)) {
                    return dbOrder;
                }
            }
        }

        OrderBaseInfo order = new OrderBaseInfo();
        //设置订单总编号
        order.setApplyId(setApplyId());
        //类型
        order.setType(serverOrder.getType());
        //获取用户id
        order.setUserId(serverOrder.getUserId());
        //初始化创建时间
        order.setAddtime(LocalDateTime.now());
        //初始化订单状态为0 = 未完结订单
        order.setOrderStatusType(0);
        //初始化状态为 0: 未支付
        order.setPayStatus(0);
        //初始化为校内
        order.setSchoolType(0);
        //初始化用户id
        order.setUserId(userInfo.getId());
        //初始化用户名
        order.setUserName(userInfo.getName());
        //初始化手机号
        order.setPhone(userInfo.getPhone());
        order.setIsSend(1);
        orderBaseInfoMapper.insert(order);
        return new SendCreateId(order.getId());
    }


    /**
     * 保存cnki 的数据
     *
     * @param searchEntity
     */
    private void saveCnki(SearchEntity searchEntity, OrderBaseInfo orderBaseInfo) {
        CnkiDetail cnkiDetail = new CnkiDetail();
        cnkiDetail.setApplyId(orderBaseInfo.getApplyId());
        cnkiDetail.setCategory(getIds(searchEntity));
        cnkiDetail.setAuthorOrder(searchEntity.getFirstAuthor());
        cnkiDetail.setTitleHref(searchEntity.getDetailsPageHref());
        cnkiDetail.setYear(searchEntity.getPublished());
        cnkiDetail.setFulltextUrl(Constants.CNKI_WAIT_HTML);
        //得到项目域名: 拼接请求地址  需要端口//  + ":" + request.getServerPort()
        String printRequestPath = request.getScheme() + "://" + request.getServerName();
        cnkiDetail.setDetailsPic(printRequestPath);
        cnkiDetail.setPdfPath("");

        //被引次数
        String quotenum = searchEntity.getQuotenum();
        if (StringUtils.isEmpty(quotenum)) {
            cnkiDetail.setCitedNum("0");
        } else {
            cnkiDetail.setCitedNum(quotenum);
        }

//        System.out.println(cnkiDetail);
        System.out.println("=================CNKI=========================");
        cnkiDetailMapper.insert(cnkiDetail);
    }

    /**
     * 获取论文清单中出现的数据库
     * 获取数据库
     *
     * @param searchEntity 封装论文清单实体类
     * @return
     */
    private String getIds(SearchEntity searchEntity) {
        HashMap<String, String> map = new HashMap<>(16);
        map.put("SCIE", "0");
        map.put("CSCD", "1");
        map.put("SSCI", "2");
        map.put("A&HCI", "3");
        map.put("CPCI-S", "4");
        map.put("CPCI-SSH", "5");
        map.put("CSSCI", "6");
        map.put("CNKI", "7");
        map.put("EI", "8");


        String source = searchEntity.getSource();
        StringBuilder idsBuilder = new StringBuilder();
        if (!StringUtils.isEmpty(source)) {
            if (source.contains(",")) {
                String[] split = source.split(",");
                if (split.length > 1) {
                    for (String s : split) {
                        if (s.contains("<")) {
                            String str = s.split("<")[0].trim();
                            str = map.get(str);
                            if (str != null) {
                                idsBuilder.append(str).append(",");
                            } else {
                                log.error("论文清单数据库筛选,有的没有匹配到1");
                                log.error("数据: " + source);
                            }
                        } else {
                            s = map.get(s.trim());
                            if (s != null) {
                                idsBuilder.append(s).append(",");
                            } else {
                                log.error("论文清单数据库筛选,有的没有匹配到2");
                                log.error("数据: " + source);
                            }
                        }
                    }
                } else {
                    source = map.get(split[0].trim());
                    if (source != null) {
                        idsBuilder.append(source);
                    } else {
                        log.error("论文清单数据库筛选,有的没有匹配到3");
                        log.error("数据: " + source);
                    }
                }
            } else {
                if (source.contains("<")) {
                    String str = source.split("<")[0].trim();
                    str = map.get(str);
                    if (str != null) {
                        idsBuilder.append(str);
                    } else {
                        log.error("论文清单数据库筛选,有的没有匹配到4");
                        log.error("数据: " + source);
                    }
                } else {
                    if ("WOS".equals(source)) {
                        idsBuilder.append(Constants.SCIE);
                    } else {
                        if ("CSCD".equals(source)) {
                            idsBuilder.append(Constants.CSCD);
                        } else {
                            source = map.get(source.trim());
                            if (!StringUtils.isEmpty(source)) {
                                idsBuilder.append(source);
                            } else {
                                log.error("论文清单数据库筛选,有的没有匹配到5");
                                log.error("数据: " + source);
                            }
                        }
                    }
                }
            }
        } else {
            log.error("来源为空...");
        }
        if (idsBuilder.toString().length() > 0) {
            String ids = idsBuilder.toString();
            if (",".equals(ids.substring(ids.length() - 1))) {
                idsBuilder = new StringBuilder();
                ids = ids.substring(0, ids.length() - 1);
                idsBuilder.append(ids);
            }
        }
        return idsBuilder.toString();
    }

    /**
     * 首页查询
     * 根据手机号, 申请号分页查询.
     *
     * @param page       当前页
     * @param rows       每页多少个
     * @param conditions 手机号/申请号
     * @return 分页+数据
     */
    @Override
    public Object findByConditions(Integer page, Integer rows, String conditions) {
        //手机号长度
        final int phoneLength = 11;
        //订单长度
        final int orderLength = 9;
        if (conditions != null) {
            QueryWrapper<OrderBaseInfo> qw = new QueryWrapper<>();
            if (conditions.length() == phoneLength) {
                qw.eq("phone", conditions);
                //结果降序
                qw.orderByDesc("apply_id");
            } else if (conditions.length() == orderLength) {
                qw.eq("apply_id", conditions);
                //结果降序
                qw.orderByDesc("apply_id");
            } else {
                return "未查询到结果";
            }
            return orderBaseInfoMapper.selectPage(new Page<OrderBaseInfo>(page, rows), qw);
        }
        return "不能为空";
    }

    /**
     * 保存我的文献
     *
     * @param searchEntity  解析实体
     * @param orderBaseInfo 订单实体
     */
    private void saveMyLiterature(SearchEntity searchEntity, OrderBaseInfo orderBaseInfo) {
        MyLiterature myLiterature = new MyLiterature();
        myLiterature.setOrderId(orderBaseInfo.getApplyId());
        myLiterature.setUserId(orderBaseInfo.getUserId());
        myLiterature.setAuthor(searchEntity.getAuthor());
        myLiterature.setLiteratureType(orderBaseInfo.getType());
        //获取论文清单中出现的数据库
        if (!StringUtils.isEmpty(searchEntity.getSource())) {
            String source = searchEntity.getSource();
            if (source.contains(",")) {
                source = source.substring(0, source.length() - 1);
            }
            myLiterature.setRepositoryId(source);
        } else {
            myLiterature.setRepositoryId("");
        }
        //第一作者...
        if (StringUtils.isEmpty(searchEntity.getFirstAuthor())) {
            String firstAuthor = searchEntity.getFirstAuthor();
            myLiterature.setFirstAuthor(firstAuthor);
        } else {
            myLiterature.setFirstAuthor("");
        }
        //标题
        myLiterature.setTitle(searchEntity.getTitle());
        //年
        myLiterature.setPublished(searchEntity.getPublished());
        //卷
        myLiterature.setVolume(searchEntity.getVolume());
        //期
        myLiterature.setIssue(searchEntity.getIssue());
        //页
        myLiterature.setPages(searchEntity.getPages());
        myLiterature.setUt(searchEntity.getUt());
//        myLiteratureService.add(myLiterature);
    }

    /**
     * 保存wos到本地
     *
     * @param searchEntity  解析实体
     * @param orderBaseInfo 订单实体
     */
    private void saveWos(SearchEntity searchEntity, OrderBaseInfo orderBaseInfo) {
        Wosdetail wosdetail = new Wosdetail();
        //获取论文清单中出现的数据库
        wosdetail.setCategory(getIds(searchEntity));

        //如果是cnki,是没有detailList的, 传个值补位
        String category = wosdetail.getCategory();
        Set<String> categorySet = null;
        if (category.contains(",")) {
            categorySet = new HashSet<>(Arrays.asList(category.split(",")));
        } else {
            categorySet = new HashSet<>();
            categorySet.add(category);
        }
        if (categorySet.contains(Constants.CNKI)) {
            wosdetail.setDetailList("CNKI");
        }

        //用户检索的标题
        wosdetail.setStitle(searchEntity.getUserSearchTitle());
        //申请号 applyId
        wosdetail.setCommissionid(orderBaseInfo.getApplyId());
        // TODO 校内增补期刊字段 添加
        //勾选的完整标题
        String title = searchEntity.getTitle();
        if (!StringUtils.isEmpty(title)) {
            wosdetail.setTitlename(title.trim());
        }
        wosdetail.setAuthor(searchEntity.getAuthor());
        //年
        wosdetail.setPub(searchEntity.getPublished());
        //set 其他数据
        setFenQv(wosdetail);
        //卷
        wosdetail.setJuan(searchEntity.getVolume());
        //期
        wosdetail.setQi(searchEntity.getIssue());
        //页
        wosdetail.setYe(searchEntity.getPages());
        //详情页链接.
        wosdetail.setTitlehref(searchEntity.getDetailsPageHref());
        //UT
        if (StringUtils.isNotEmpty(searchEntity.getUt())) {
            wosdetail.setUt(searchEntity.getUt());
        } else {
            wosdetail.setUt("not");
        }
        //来源
        wosdetail.setPeriodical(searchEntity.getPeriodical());
        wosdetail.setArticleType(searchEntity.getArticleType());

        //cnki的下载被引的参数
        //wosdetail.setCitedOther(searchEntity.getCnkiCiteOtherData());

        //第一, 第二作者
        String firstAuthor = searchEntity.getFirstAuthor();
        if (!StringUtils.isEmpty(firstAuthor)) {
            if (",".equals(firstAuthor.substring(firstAuthor.length() - 1))) {
                firstAuthor = firstAuthor.substring(0, firstAuthor.length() - 1);
                //用户勾选的作者信息
                wosdetail.setSearchuse(firstAuthor);
            } else {
                wosdetail.setSearchuse("其他");
            }
        } else {
            wosdetail.setSearchuse("其他");
        }

        //被引次数
        String quotenum = searchEntity.getQuotenum();
        if (StringUtils.isEmpty(quotenum)) {
            wosdetail.setCitedNum("0");
        } else {
            wosdetail.setCitedNum(quotenum);
        }

        //得到项目域名: 拼接请求地址
        String printRequestPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        wosdetail.setDetailsPic(printRequestPath);

        //抓详情页做区分
        category = wosdetail.getCategory();
        Set<String> categorys = null;
        if (category.contains(",")) {
            categorys = new HashSet<>(Arrays.asList(category.split(",")));
        } else {
            categorys = new HashSet<>();
            categorys.add(category);
        }
        boolean wosBoo = categorys.contains(Constants.CSCD)
                || categorys.contains(Constants.SCIE)
                || categorys.contains(Constants.SSCI)
                || categorys.contains(Constants.ISTP)
                || categorys.contains(Constants.ISSHP)
                || categorys.contains(Constants.AHCI);

        if (categorys.contains(Constants.CNKI)) {
            //cnki = 待抓详情页
            wosdetail.setFulltextUrl("cnki");
        } else if (categorys.contains(Constants.EI)) {
            //ei的详情页是 模板+json, 不好弄详情页
            wosdetail.setFulltextUrl("");
            wosdetail.setDetailsPic("");
            //判断文章是否被收录
            whetherArticleEntered.whetherEntered(wosdetail);
        } else if (categorys.contains(Constants.CSSCI)) {
            //cssci 的详情页是 模板+json, 不好弄详情页
            wosdetail.setFulltextUrl("");
            wosdetail.setDetailsPic("");
        } else if (wosBoo) {
            //wos = 待抓详情页
            wosdetail.setFulltextUrl("wos");
        }

        //判断是否计算被引
        if (searchEntity.getQuotenum() != null) {
            if (!"0".equals(searchEntity.getQuotenum())) {
                //3 = 待计算被引
                wosdetail.setCiteStatus("03");
            } else {
                //6 = 无被引次数
                wosdetail.setCiteStatus("06");
            }
        } else {
            //6 = 无被引次数
            wosdetail.setCiteStatus("06");
        }
        //添加
        wosdetailMapper.insert(wosdetail);
    }

    /**
     * cpcmi-ssh 没有影响因子,及分区
     * 默认 2018-9 年前为A2 之后的为 B1
     *
     * @param wosDetail 本地wos
     * @return
     */
    private void setFenQv(Wosdetail wosDetail) {
        String category = wosDetail.getCategory();
        Set<String> categorys = new HashSet<String>();
        if (category.contains(",")) {
            categorys = new HashSet<>(Arrays.asList(category.split(",")));
        } else {
            categorys.add(category);
        }
        if (categorys.contains(Constants.ISSHP)) {
            wosDetail.setJcr("");
            wosDetail.setZky("");
            //2018年9月前为A2 后 为B1
            if (!StringUtils.isEmpty(wosDetail.getPub())) {
                String pub = wosDetail.getPub();
                Integer year = null;
                Integer month = null;
                if (pub.contains("-")) {
                    if (pub.contains(" ")) {
                        String[] split1 = pub.split("-");
                        String[] split = pub.split(" ");
                        year = Integer.valueOf(split[split.length - 1]);
                        month = Integer.valueOf(split1[1]);
                    }
                } else if (pub.contains(" ")) {
                    String[] split = pub.split(" ");
                    month = Integer.valueOf(getMonthNum(split[0]));
                    year = Integer.valueOf(split[split.length - 1]);
                } else {
                    if (pub.contains(",")) {
                        String[] split = pub.split(",");
                        if (!StringUtils.isEmpty(split[0])) {
                            month = Integer.valueOf(split[0]);
                        }
                        year = Integer.valueOf(split[1]);
                    } else {
                        year = Integer.valueOf(pub);
                    }
                }
                if (year != null) {
                    if (month != null) {
                        if (year <= 2018) {
                            if (year == 2018) {
                                if (month <= 9) {
                                    wosDetail.setYinzi1("A2");
                                } else {
                                    wosDetail.setYinzi1("B1");
                                }
                            } else {
                                wosDetail.setYinzi1("A2");
                            }
                        } else {
                            wosDetail.setYinzi1("B1");
                        }
                    } else {
                        if (year <= 2018) {
                            wosDetail.setYinzi1("A2");
                        } else {
                            wosDetail.setYinzi1("B1");
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据订单查询订单的状态
     *
     * @param orderId 订单id
     * @return
     */
    @Override
    public List<ReturnOrderStatus> getOrderStatus(Integer orderId) {
        List<ReturnOrderStatus> result = new ArrayList<>(10);
        // 5, 8 退回状态
        Integer[] backStatus = {5, 8};
        ReturnOrderStatus returnOrderStatus = null;
        OrderBaseInfo orderBaseInfo = orderBaseInfoMapper.selectById(orderId);

        Object uidObj = request.getAttribute("u_id");
        CheckUtil.notNull(uidObj, "操作超时请重新登录");
        CheckUtil.check(orderBaseInfo.getUserId().equals(Integer.valueOf(uidObj + "")), "非法操作订单");

        Integer status = orderBaseInfo.getOrderStatusType();
        //草稿的订单直接返回
        if (status != null && status.equals(88)) {
            returnOrderStatus = new ReturnOrderStatus();
            returnOrderStatus.setTime(timeFormatToString(orderBaseInfo.getAddtime()));
            returnOrderStatus.setStatus("草稿订单");
            result.add(returnOrderStatus);
            return result;
        }

        List<OrderIndexTime> orderStatusList
                = orderIndexTimeMapper.selectList(new QueryWrapper<OrderIndexTime>()
                .eq("order_id", orderId)
                .orderByDesc("id"));
        if (orderStatusList.size() > 0) {
            //去重用的集合
            Set<Integer> set = new HashSet<Integer>();
            for (OrderIndexTime statusEntity : orderStatusList) {
                Integer statusId = statusEntity.getOrderStatus();
                if (Arrays.asList(backStatus).contains(statusId)) {
                    statusId = statusId - 1;
                }
                //获取中文
                OrderStatus orderStatus = orderStatusMapper.selectById(statusId);
                LocalDateTime statusTime = statusEntity.getAddTime();
                String statusName = orderStatus.getOrderStatusName();
                //多个退回状态
                if (statusId == 2) {
                    returnOrderStatus = new ReturnOrderStatus();
                    returnOrderStatus.setTime(timeFormatToString(statusTime));
                    returnOrderStatus.setStatus(statusName);
                    returnOrderStatus.setBackMessage(statusEntity.getReason());
                    result.add(returnOrderStatus);
                } else {
                    //不是退回状态, 则对状态去重,不重复则添加
                    if (!set.contains(statusId)) {
                        set.add(statusId);
                        //封装
                        returnOrderStatus = new ReturnOrderStatus();
                        returnOrderStatus.setTime(timeFormatToString(statusTime));
                        returnOrderStatus.setStatus(statusName);
                        returnOrderStatus.setBackMessage(statusEntity.getReason());
                        result.add(returnOrderStatus);
                    }
                }
            }
        }
        // 降序的所以最后添加这个 创建订单.
        returnOrderStatus = new ReturnOrderStatus();
        returnOrderStatus.setTime(timeFormatToString(orderBaseInfo.getAddtime()));
        returnOrderStatus.setStatus("创建订单");
        result.add(returnOrderStatus);
        return result;
    }

    /**
     * 查询用户下所有委托单(我的委托单页)
     *
     * @param page   当前页
     * @param rows   没也多少个
     * @param userId 用户id
     * @param type   订单类型
     * @return
     */
    @Override
    public IPage<OrderBaseInfo> findByUserId(HttpServletRequest request, Integer page, Integer rows, Integer userId,
                                             Integer type) {
        CheckUtil.check(type != null, "类型异常type:" + type);
        CheckUtil.check(userId != null, "用户异常id:" + userId);

        Object uidObj = request.getAttribute("u_id");
        CheckUtil.notNull(uidObj, "操作超时请重新登录");
        userId = Integer.valueOf(uidObj + "");

        QueryWrapper<OrderBaseInfo> qw = new QueryWrapper<OrderBaseInfo>();
        qw.select("id", "apply_id", "project_no", "assign_back", "school_type", "chaxin_contract",
                "type", "wtr_name", "addtime", "endtime", "total_fee",
                "order_status_type", "user_id", "gy_id", "entrust_institutions", "paper_list", "result_report_word");
        qw.orderByDesc("apply_id");
        qw.eq("type", type);
        qw.eq("user_id", userId);
        qw.and(wrapper -> wrapper.ne("order_status_type", 0));

        IPage<OrderBaseInfo> userOrdersPage = orderBaseInfoMapper.selectPage(new Page<>(page, rows), qw);
        List<OrderBaseInfo> order = userOrdersPage.getRecords();
        if (order.size() > 0) {
            for (OrderBaseInfo teamOrder : order) {
                UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>()
                        .eq("id", teamOrder.getUserId()).eq("is_delete",
                                0));
                //院系
                teamOrder.setDepartments(userInfo.getDepartments());

                //我的委托单编号展示
                String projectNo = teamOrder.getProjectNo();
                if (StringUtils.isNotEmpty(projectNo)) {
                    teamOrder.setApplyId(projectNo);
                }

                //馆员id
                Integer gyId = teamOrder.getGyId();
                if (gyId != null) {
                    Employee employee = employeeMapper.selectById(gyId);
                    if (employee != null) {
                        String userName = employee.getUserName();
                        teamOrder.setAcceptPerson(userName);
                    } else {
                        teamOrder.setAcceptPerson("匿名");
                    }

                } else {
                    if (teamOrder.getOrderStatusType() == 2) {
                        teamOrder.setAcceptPerson("无");
                    } else if (teamOrder.getOrderStatusType() == 3) {
                        teamOrder.setAcceptPerson("待指派");
                    } else {
                        teamOrder.setAcceptPerson("待受理");
                    }
                }
                //完成时间为空时不展示价格
                LocalDateTime endTime = teamOrder.getEndtime();
                if (endTime == null) {
                    teamOrder.setTotalFee(0);
                } else {
                    if (StringUtils.isEmpty(String.valueOf(endTime))) {
                        teamOrder.setTotalFee(0);
                    }
                }

                //查询当前订单的留言状态(数量)
                List<Message> messages = messageMapper.selectList(new QueryWrapper<Message>()
                        .eq("order_id", teamOrder.getId()));
                if (messages == null || messages.size() == 0) {
                    teamOrder.setMessageSize(0);
                } else {
                    Integer num = 0;
                    for (Message message : messages) {
                        //判断未读状态  0 == 未读
                        Integer status = message.getStatus();
                        Integer index = 0;
                        if (index.equals(status)) {
                            //判断是不是自己的留言, 自己的留言不显示未读
                            Integer replyId = message.getReplyId();
                            if (replyId == null) {
                                continue;
                            }
                            if (replyId != 0) {
                                num += 1;
                            }
                        }
                    }
                    teamOrder.setMessageSize(num);
                }

                //订单的状态展示
                Integer status = teamOrder.getOrderStatusType();
                if (status == 88) {
                    teamOrder.setOrderStatusName("草稿/待修改");
                    teamOrder.setAcceptPerson("");
                } else if (status == 10) {
                    teamOrder.setOrderStatusName("已完成");
                } else if (status >= 3) {
                    teamOrder.setOrderStatusName("进行中");
                } else if (status == 1) {
                    teamOrder.setOrderStatusName("新订单");
                } else if (status == 2) {
                    teamOrder.setOrderStatusName("订单被退回");
                }
                // 2024年7月16日11:08:18 进行修改订单支付测试显示支付状态
                Integer id = teamOrder.getId();

            }
        } else {
            log.error("当前类别未查询到结果");
        }
        userOrdersPage.setRecords(order);
        return userOrdersPage;
    }

    /**
     * 发送短信,通知接单员
     *
     * @param orderBaseInfo 订单实体类
     */
    @Override
    public void sendMessageByJdy(OrderBaseInfo orderBaseInfo) {
        CheckUtil.check(orderBaseInfo.getApplyId() != null, "订单号为空");
        //存储多个电话号码集合
        List<String> phoneList = new ArrayList<>();
        //获取权限
        TRole role = roleMapper.selectOne(new QueryWrapper<TRole>().eq("name", "接单员"));
        //通过权限找到接单员
        List<Employee> employeeList = employeeMapper.selectList(new QueryWrapper<Employee>().eq("role",
                role.getId()));
        if (employeeList.size() > 0) {
            for (Employee employee : employeeList) {
                //将接单员的电话添加到集合
                phoneList.add(employee.getMobile());
            }
        }
        CheckUtil.check(phoneList.size() > 0 && orderBaseInfo.getApplyId() != null, "发送失败");
        sendSms.generatorSms(7, phoneList, orderBaseInfo.getApplyId());
    }

    /**
     * 委托单 - 解析检索范围页 用户勾选的值
     *
     * @param orderBaseInfo 订单实体
     */
    @Override
    public QueryScopeDetail queryScopeMap(OrderBaseInfo orderBaseInfo) {
        if (StringUtils.isNotEmpty(orderBaseInfo.getRepositoryPartitionIds())) {

            String authorNameEn = orderBaseInfo.getRepositoryPartitionIds();
            QueryScopeDetail queryScopeDetail = JSON.parseObject(authorNameEn, QueryScopeDetail.class);
            //勾选的期刊分区影响因子
            if (queryScopeDetail != null) {
                return queryScopeDetail;
            }
        }
        return null;
    }

    /**
     * 获取订单下上传的所有文件.
     *
     * @param orderBaseInfo
     * @return 返回所有用户上传的文件名(封装的实体)
     */
    @Override
    public List<OrderFileList> getUserUpload(OrderBaseInfo orderBaseInfo) {
        //存储当前下单下所有上传的文件
        List<OrderFileList> fileNameList = new ArrayList<>();

        orderBaseInfo = orderBaseInfoMapper.selectById(orderBaseInfo.getId());

        //上传的wos导出的文章txt 已解析的文件
        String quotefile = orderBaseInfo.getQuotefile();
        if (StringUtils.isNotEmpty(quotefile)) {
            if (quotefile.contains(";")) {
                String[] split = quotefile.split(";");
                for (String str : split) {
                    OrderFileList entity = getFileName(str);
                    entity.setType("WebOfScience导出的文章txt");
                    entity.setFilePath(str);
                    fileNameList.add(entity);
                }
            } else {
                OrderFileList entity = getFileName(quotefile);
                entity.setType("WebOfScience导出的文章txt");
                entity.setFilePath(quotefile);
                fileNameList.add(entity);
            }
        }
        //上传的查新合同
        String uploadReport = orderBaseInfo.getUploadReport();
        if (StringUtils.isNotEmpty(uploadReport)) {
            if (uploadReport.contains(";")) {
                String[] split = uploadReport.split(";");
                for (String str : split) {
                    OrderFileList entity = getFileName(str);
                    entity.setType("查新合同");
                    entity.setFilePath(str);
                    fileNameList.add(entity);
                }
            } else {
                OrderFileList entity = getFileName(uploadReport);
                entity.setType("查新合同");
                entity.setFilePath(uploadReport);
                fileNameList.add(entity);
            }
        }
        //查新资料
        String dataDirectory = orderBaseInfo.getDataDirectory();
        if (StringUtils.isNotEmpty(dataDirectory)) {
            if (dataDirectory.contains(";")) {
                String[] split = dataDirectory.split(";");
                for (String str : split) {
                    OrderFileList entity = getFileName(str);
                    entity.setType("查新资料");
                    entity.setFilePath(str);
                    fileNameList.add(entity);
                }
            } else {
                OrderFileList entity = getFileName(dataDirectory);
                entity.setType("查新资料");
                entity.setFilePath(dataDirectory);
                fileNameList.add(entity);
            }
        }
        //上传的缴费凭证
        String payJpg = orderBaseInfo.getPayJpg();
        if (StringUtils.isNotEmpty(payJpg)) {
            if (payJpg.contains(";")) {
                String[] split = payJpg.split(";");
                for (String str : split) {
                    OrderFileList entity = getFileName(str);
                    entity.setType("缴费凭证");
                    entity.setFilePath(str);
                    fileNameList.add(entity);
                }
            } else {
                OrderFileList entity = getFileName(payJpg);
                entity.setType("缴费凭证");
                entity.setFilePath(payJpg);
                fileNameList.add(entity);
            }
        }
        return fileNameList;
    }

    /**
     * 获取文件名
     * {@link OrderServiceImpl#getUserUpload(OrderBaseInfo)}
     *
     * @param str
     * @return
     */
    private OrderFileList getFileName(String str) {
        str = str.replace(" ", "");
        OrderFileList entity = new OrderFileList();

        //切除掉路径保留文件名
        String[] split = str.split("/");
        str = split[split.length - 1];

        if (str.contains("$")) {
            //后缀
            String prefix = ".unknown";
            if (str.contains(".")) {
                prefix = str.substring(str.lastIndexOf("."));
            }
            //文件名 + 毫秒
            String[] fileSplit2 = str.split("\\$");
            str = fileSplit2[0];
            str = str.replace(" ", "");
            //判断文件名是不是空的
            if (StringUtils.isEmpty(str)) {
                str = "unknown";
            }
            //判断有没有被转义, 这是在上传的时候转义的
            if (str.contains("\\u")) {
                str = UniCodeUtil.dCode(str);
            }
            if (str.contains("%")) {
                try {
                    str = URLDecoder.decode(str, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    log.error("URLDecoder 用户上传的文件名失败了");
                    e.printStackTrace();
                }
            }
            entity.setFileName(str);
        }
        return entity;
    }

    /**
     * 格式化localDateTime 中文的年月日
     *
     * @param localDate LocalDateTime
     * @return
     */
    private String timeFormatToString(LocalDateTime localDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDate.format(formatter);
    }

    /**
     * 将英文月份简写, 转换为数字月份
     *
     * @param month 英文月
     * @return
     */
    private String getMonthNum(String month) {
        if (!StringUtils.isEmpty(month)) {
            HashMap<String, String> monthEnMap = new HashMap<>(16);
            monthEnMap.put("jan", "1");
            monthEnMap.put("feb", "2");
            monthEnMap.put("mar", "3");
            monthEnMap.put("apr", "4");
            monthEnMap.put("may", "5");
            monthEnMap.put("jun", "6");
            monthEnMap.put("jul", "7");
            monthEnMap.put("aug", "8");
            monthEnMap.put("sept", "9");
            monthEnMap.put("oct", "10");
            monthEnMap.put("nov", "11");
            monthEnMap.put("dec", "12");
            String monthNum = monthEnMap.get(month.toLowerCase());
            if (!StringUtils.isEmpty(monthNum)) {
                return monthNum;
            }
        }
        return "";
    }

    /**
     * 校验订单类型.及各种数据
     *
     * @param orderBaseInfo 订单
     */
    private void orderValidation(OrderBaseInfo orderBaseInfo) {

        //委托人 去空格
        if (StringUtils.isNotEmpty(orderBaseInfo.getWtrName())) {
            orderBaseInfo.setWtrName(orderBaseInfo.getWtrName().replaceAll(" ", ""));
        }


        //目的描述
        String purposeDescribe = orderBaseInfo.getPurposeDescribe();
        if (StringUtils.isNotEmpty(purposeDescribe)) {
            if (purposeDescribe.length() >= 255) {
                CheckUtil.check(false, "超长了, 请简短您的目的描述");
            }
            if (purposeDescribe.length() < 5) {
                CheckUtil.check(false, "请详细描述此目的");
            }
        }

        //报告份数
        Integer reportNum = orderBaseInfo.getReportNum();
        if (reportNum != null) {
            if (reportNum < 1 || reportNum > 100) {
                CheckUtil.check(false, "请确认您需要的报告数量");
            }
        }

    }


}
